/***************************************************************************************
* Copyright (c) 2014-2022 Zihao Yu, Nanjing University
*
* NEMU is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*          http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*
* See the Mulan PSL v2 for more details.
***************************************************************************************/

///#include <isa.h>
//#include <cpu/cpu.h>
//#include <readline/readline.h>
//#include <readline/history.h>
#include "../include/sdb.h"
#include "../include/paddr.h"
#include "../include/common.h"
#include "../include/reg.h"
#include <elf.h>
//#include <utils.h>

static int is_batch_mode = false;
void init_regex();
void init_wp_pool();

//存储符号表中的一行
typedef struct symtable{
	char name[32]; // func name, 32 should be enough
	paddr_t addr;
	unsigned char info;
	paddr_t size;
} symbol_table;
static symbol_table *symbol_tables = NULL; // dynamic allocated

/* We use the `readline' library to provide more flexibility to read from stdin. */
char* rl_gets() {
  static char *line_read = NULL;

  if (line_read) {
    free(line_read);
    line_read = NULL;
  }

  line_read = readline("(nemu) ");

  if (line_read && *line_read) {
    add_history(line_read);
  }

  return line_read;
}

int cmd_c(char *args) {
  //cpu_exec(-1);
  while(npc_state.state == NPC_RUNNING || npc_state.state == NPC_STOP){
    exec_once();
  }
  return 0;
}


int cmd_q(char *args) {
  npc_state.state = NPC_QUIT;
  return -1;
}

int cmd_si(char *args) {
  int n;
  if(args == NULL)
    n = 1;
  else
    sscanf(args,"%d",&n);

  for(int i = 0; i < n; i = i + 1){
    if(npc_state.state == NPC_RUNNING || npc_state.state == NPC_STOP)
      exec_once();
  }
  return 0;
}

int cmd_info(char *args) {
  char cmd;
  sscanf(args,"%c",&cmd);

  if(cmd == 'r')
    isa_reg_display();
  else if(cmd == 'w')
    //print_wp();
    ;
  return 0;
}

int cmd_x(char *args) {
  int n;    // N
  int expr; // EXPR
  int i;
  sscanf(args,"%d %x",&n,&expr);
  
  for(i=0;i<n;i++)
  {
    printf("0x%08x: 0x%08x \n",expr,pmem_read(expr,4));
    expr += 4;
  }
  
  return 0;
}

int cmd_p(char *args) {
  word_t result;
  bool success;

  //result = expr(args,&success);
  if(success)
    printf("SUM result:%d\r\n",result);
  
  return 0;
}

int cmd_w(char *args) {
  //cmd_watch(args);
  return 0;
}

int cmd_d(char *args) {
	//cmd_delete(args);
	return 0;
}



static struct {
  const char *name;
  const char *description;
  int (*handler) (char *);
} cmd_table [] = {
  { "help", "Display information about all supported commands", cmd_help },
  { "c", "Continue the execution of the program", cmd_c },
  { "q", "Exit NEMU", cmd_q },

  /* TODO: Add more commands */
  { "si", "Single Step", cmd_si },
  { "info", "Print", cmd_info },
  { "x", "Scan Mem", cmd_x },
  { "p", "EXPR", cmd_p },
  { "w", "Set Point", cmd_w },
  { "d", "Delet Point", cmd_d },

};

#define NR_CMD ARRLEN(cmd_table)

int cmd_help(char *args) {
  /* extract the first argument */
  char *arg = strtok(NULL, " ");
  int i;

  if (arg == NULL) {
    /* no argument given */
    for (i = 0; i < NR_CMD; i ++) {
      printf("%s - %s\n", cmd_table[i].name, cmd_table[i].description);
    }
  }
  else {
    for (i = 0; i < NR_CMD; i ++) {
      if (strcmp(arg, cmd_table[i].name) == 0) {
        printf("%s - %s\n", cmd_table[i].name, cmd_table[i].description);
        return 0;
      }
    }
    printf("Unknown command '%s'\n", arg);
  }
  return 0;
}

void sdb_set_batch_mode() {
  is_batch_mode = true;
}

void sdb_mainloop() {
  if (is_batch_mode) {
    cmd_c(NULL);
    return;
  }

  for (char *str; (str = rl_gets()) != NULL; ) {
    char *str_end = str + strlen(str);

    /* extract the first token as the command */
    char *cmd = strtok(str, " ");
    if (cmd == NULL) { continue; }

    /* treat the remaining string as the arguments,
     * which may need further parsing
     */
    char *args = cmd + strlen(cmd) + 1;
    if (args >= str_end) {
      args = NULL;
    }

#ifdef CONFIG_DEVICE
    extern void sdl_clear_event_queue();
    sdl_clear_event_queue();
#endif

    int i;
    for (i = 0; i < NR_CMD; i ++) {
      if (strcmp(cmd, cmd_table[i].name) == 0) {
        if (cmd_table[i].handler(args) < 0) { return; }
        break;
      }
    }

    if (i == NR_CMD) { printf("Unknown command '%s'\n", cmd); }
  }
}

void init_sdb() {
  /* Compile the regular expressions. */
  //init_regex();

  /* Initialize the watchpoint pool. */
  //init_wp_pool();
}

// int symbol_cnt = 0;
// //read elf
// void read_elf(const char *elf_file){
//   if (elf_file == NULL)
//     return ;
//   // 打开ELF文件
//   FILE *fp = fopen(elf_file, "rb");
//   assert(fp);

//   //Call Elf32_Ehdr and read Elf32_Ehdr
//   Elf32_Ehdr elf_header;
//   //Only read 1 Elf32_Ehdr member
//   if (fread(&elf_header, sizeof(Elf32_Ehdr), 1, fp) <= 0) {
//     fclose(fp);
//     assert(1);
//   }
//   //printf("e_phoff = %x\n",elf_header.e_phoff);
//   //printf("e_shoff = %x\n",elf_header.e_shoff);

//   //从文件的开头跳转到Section header
//   fseek(fp, elf_header.e_shoff, SEEK_SET);
//   //Call Elf32_Shdr and read Elf32_Shdr
//   Elf32_Shdr strtab_header;
//   //Find strtab————>type:STRTAB
//   while(strtab_header.sh_type != SHT_STRTAB){
//     if (fread(&strtab_header, sizeof(Elf32_Shdr), 1, fp) <= 0) {
//       fclose(fp);
//       assert(1);
//     }
//   }
//   //printf("sh_idex = %d\n",strtab_header.sh_name);
//   //printf("sh_type = %d\n",strtab_header.sh_type);
//   //printf("sh_size = %d\n",strtab_header.sh_size);
//   //printf("sh_offset = %x\n",strtab_header.sh_offset);

//   //从文件的开头跳转到StrTab，并读取strtab的内容
//   char *strtab = malloc(strtab_header.sh_size);
//   fseek(fp, strtab_header.sh_offset, SEEK_SET);
//   if (fread(strtab, strtab_header.sh_size, 1, fp) <= 0) {
//     fclose(fp);
//     assert(1);
//   }
//   //puts(strtab);

//   //Find symtab————>type:SYMTAB
//   //从文件的开头跳转到Section header
//   Elf32_Shdr symtab_header;
//   fseek(fp, elf_header.e_shoff, SEEK_SET);
//   while(symtab_header.sh_type != SHT_SYMTAB){
//     if (fread(&symtab_header, sizeof(Elf32_Shdr), 1, fp) <= 0) {
//       fclose(fp);
//       assert(1);
//     }
//   }
//   //printf("sh_idex = %d\n",symtab_header.sh_name);
//   //printf("sh_type = %d\n",symtab_header.sh_type);
//   //printf("sh_offset = %x\n",symtab_header.sh_offset);

//   //Call Elf32_Sym
//   Elf32_Sym symbol;
  
//   size_t num_symbols = symtab_header.sh_size / symtab_header.sh_entsize;  //entry num
//   symbol_tables = malloc(num_symbols * sizeof(symbol_table));
//   //Find symbol
//   fseek(fp, symtab_header.sh_offset, SEEK_SET);

//   for(int i = 0; i < num_symbols; i++)
//   {
//     if (fread(&symbol, sizeof(Elf32_Sym), 1, fp) <= 0) {
//       fclose(fp);
//       assert(1);
//     }
//     //Get name
//     const char *name = strtab + symbol.st_name;
//     //Judge st_info == STT_FUNC
//     if (ELF32_ST_TYPE(symbol.st_info) == STT_FUNC) {
//       strncpy(symbol_tables[symbol_cnt].name, name, sizeof(symbol_tables[symbol_cnt].name)-1);
//       symbol_tables[symbol_cnt].addr = symbol.st_value;
//       printf("addr = %x \n",symbol_tables[symbol_cnt].addr);
//       symbol_tables[symbol_cnt].info = symbol.st_info;
//       symbol_tables[symbol_cnt].size = symbol.st_size;
//       symbol_cnt++;
// 		}
//   }
//   printf("Load Elf Success!! \n");
//   fclose(fp);
//   free(strtab);
// }

// int call_depth;
// void ftrace_call (paddr_t pc , paddr_t dnpc){

//   //printf("addr = %x \n",symbol_tables[0].addr);
//   if (symbol_tables == NULL) return;
//   for (int i = 0; i < symbol_cnt; i++) {
// 		if(symbol_tables[i].addr == dnpc)
//     {
//       printf("0x%08x:", pc);

//       for(int k = 0; k < call_depth; k++) printf("  ");
//       printf("call  [%s@0x%08x]\n", symbol_tables[i].name, symbol_tables[i].addr);

//       call_depth++;
//     }
// 	}
// }

// void ftrace_ret (paddr_t pc){

//   //printf("addr = %x \n",symbol_tables[0].addr);
//   if (symbol_tables == NULL) return;
//   for (int i = 0; i < symbol_cnt; i++) {
// 		if(symbol_tables[i].addr <= pc && pc < symbol_tables[i].addr + symbol_tables[i].size)
//     {
//       printf("0x%08x:", pc);
//       call_depth--;

//       for(int k = 0; k < call_depth; k++) printf("  ");
//       printf("ret   [%s@0x%08x]\n", symbol_tables[i].name, symbol_tables[i].addr);

      
//     }
// 	}
// }


